package pl.edu.agh.neuraleconomy.dataimporter.xls;

import java.io.InputStream;
import java.util.Date;
import java.util.List;

import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;
import org.apache.poi.ss.usermodel.Cell;

import pl.edu.agh.neuraleconomy.common.utils.DateUtils;
import pl.edu.agh.neuraleconomy.model.exchange.Exchange;
import pl.edu.agh.neuraleconomy.persistence.base.DaoProvider;
import pl.edu.agh.neuraleconomy.persistence.exchange.CompanyDao;
import pl.edu.agh.neuraleconomy.persistence.exchange.CurrencyDao;
import pl.edu.agh.neuraleconomy.persistence.exchange.ExchangeDao;

public class Importer {
	private Logger logger = Logger.getLogger(getClass());
	private ExchangeDao exchangeDao = DaoProvider.getExchangeDao();
	private CompanyDao companyDao = DaoProvider.getCompanyDao();
	private CurrencyDao currencyDao = DaoProvider.getCurrencyDao();
	private HistoryDataDownloader downloader = new HistoryDataDownloader();
	private XlsDataParser parser = new XlsDataParser();
	

	public void importData(Date from, Date to) {	
		while (from.compareTo(to) <= 0) {
			importForDate(from);
			from = DateUtils.addDays(from, 1);
		}
	}

	public void importForDate(Date date) {
		InputStream xlsStream = null;
		try {
			xlsStream = downloader.getHistoryByDate(date);
			List<List<Cell>> rows = parser.processSheet(xlsStream);
			for (int rowNum = 1; rowNum < rows.size(); rowNum++) {
				try {
					List<Cell> row = rows.get(rowNum);
					processRow(row, date);
				} catch (Exception e) {
					logger.error("Nie udalo sie zaimportowac wiersza " + rowNum, e);
				}
			}
		} catch (Exception e) {
			logger.error("Nie udalo sie zaimportowac danych dla " + date, e);
		} finally {
			IOUtils.closeQuietly(xlsStream);
		}
	}

	private void processRow(List<Cell> row, Date date) {
		Exchange e = new Exchange();
		e.setDate(date);
		e.setCompany(companyDao.getByNameOrCreate(parser.getStringValue(row.get(1))));
		e.setCurrency(currencyDao.getByNameOrCreate(parser.getStringValue(row.get(3))));
		e.setOpeningPrice(parser.getNumericValue(row.get(4)));
		e.setMaxPrice(parser.getNumericValue(row.get(5)));
		e.setMinPrice(parser.getNumericValue(row.get(6)));
		e.setClosingPrice(parser.getNumericValue(row.get(7)));
		e.setTransactions(parser.getNumericValue(row.get(10)).intValue());
		e.setTurnover(parser.getNumericValue(row.get(11)));
		exchangeDao.create(e);
	}

}
